// 单位定义
const units = {
    length: {
        'mm': { name: '毫米', factor: 0.001 },
        'cm': { name: '厘米', factor: 0.01 },
        'm': { name: '米', factor: 1 },
        'km': { name: '千米', factor: 1000 },
        'in': { name: '英寸', factor: 0.0254 },
        'ft': { name: '英尺', factor: 0.3048 },
        'yd': { name: '码', factor: 0.9144 },
        'mi': { name: '英里', factor: 1609.344 }
    },
    temperature: {
        'c': { name: '摄氏度', factor: 1, offset: 0 },
        'f': { name: '华氏度', factor: 5/9, offset: -32 },
        'k': { name: '开尔文', factor: 1, offset: -273.15 }
    },
    weight: {
        'mg': { name: '毫克', factor: 0.000001 },
        'g': { name: '克', factor: 0.001 },
        'kg': { name: '千克', factor: 1 },
        't': { name: '吨', factor: 1000 },
        'lb': { name: '磅', factor: 0.45359237 },
        'oz': { name: '盎司', factor: 0.028349523125 }
    },
    area: {
        'mm2': { name: '平方毫米', factor: 0.000001 },
        'cm2': { name: '平方厘米', factor: 0.0001 },
        'm2': { name: '平方米', factor: 1 },
        'ha': { name: '公顷', factor: 10000 },
        'km2': { name: '平方千米', factor: 1000000 },
        'in2': { name: '平方英寸', factor: 0.00064516 },
        'ft2': { name: '平方英尺', factor: 0.09290304 },
        'ac': { name: '英亩', factor: 4046.8564224 }
    },
    volume: {
        'ml': { name: '毫升', factor: 0.001 },
        'l': { name: '升', factor: 1 },
        'm3': { name: '立方米', factor: 1000 },
        'gal': { name: '加仑', factor: 3.78541 },
        'qt': { name: '夸脱', factor: 0.946353 },
        'pt': { name: '品脱', factor: 0.473176 },
        'fl-oz': { name: '液量盎司', factor: 0.0295735 }
    },
    currency: {
        'CNY': { name: '人民币', rate: 1 },
        'USD': { name: '美元', rate: 0.14 },
        'EUR': { name: '欧元', rate: 0.13 },
        'GBP': { name: '英镑', rate: 0.11 },
        'JPY': { name: '日元', rate: 21.5 }
    }
};

// DOM 元素
const fromValue = document.getElementById('fromValue');
const toValue = document.getElementById('toValue');
const fromUnit = document.getElementById('fromUnit');
const toUnit = document.getElementById('toUnit');
const typeBtns = document.querySelectorAll('.type-btn');
const swapBtn = document.querySelector('.swap-btn');
const historyList = document.getElementById('historyList');
const clearHistoryBtn = document.getElementById('clearHistory');
const themeToggle = document.getElementById('themeToggle');
const visualFromValue = document.getElementById('visualFromValue');
const visualFromUnit = document.getElementById('visualFromUnit');
const visualToValue = document.getElementById('visualToValue');
const visualToUnit = document.getElementById('visualToUnit');
const clearTranslationHistoryBtn = document.getElementById('clearTranslationHistory');

let currentType = 'length';
let conversionHistory = [];

// 深色模式切换
themeToggle.addEventListener('change', () => {
    document.body.setAttribute('data-theme', themeToggle.checked ? 'dark' : 'light');
    localStorage.setItem('theme', themeToggle.checked ? 'dark' : 'light');
});

// 初始化主题
const savedTheme = localStorage.getItem('theme');
if (savedTheme) {
    themeToggle.checked = savedTheme === 'dark';
    document.body.setAttribute('data-theme', savedTheme);
}

// 初始化单位选择器
function initializeUnits(type) {
    fromUnit.innerHTML = '';
    toUnit.innerHTML = '';
    
    Object.entries(units[type]).forEach(([key, value]) => {
        const fromOption = document.createElement('option');
        const toOption = document.createElement('option');
        
        fromOption.value = key;
        fromOption.textContent = `${value.name} (${key})`;
        toOption.value = key;
        toOption.textContent = `${value.name} (${key})`;
        
        fromUnit.appendChild(fromOption);
        toUnit.appendChild(toOption);
    });
    
    // 设置默认目标单位
    const defaultUnits = {
        length: 'cm',
        temperature: 'f',
        weight: 'kg',
        area: 'm2',
        volume: 'l',
        currency: 'USD'
    };
    
    toUnit.value = defaultUnits[type];
    updateVisualization();
}

// 更新可视化显示
function updateVisualization() {
    const fromUnitKey = fromUnit.value;
    const toUnitKey = toUnit.value;
    const value = parseFloat(fromValue.value) || 0;
    
    visualFromValue.textContent = value;
    visualFromUnit.textContent = units[currentType][fromUnitKey].name;
    visualToValue.textContent = parseFloat(toValue.value) || 0;
    visualToUnit.textContent = units[currentType][toUnitKey].name;
}

// 转换函数
function convert() {
    const value = parseFloat(fromValue.value);
    if (isNaN(value)) {
        toValue.value = '';
        updateVisualization();
        return;
    }

    const fromUnitKey = fromUnit.value;
    const toUnitKey = toUnit.value;
    let result;

    if (currentType === 'temperature') {
        // 温度转换需要特殊处理
        const fromUnit = units.temperature[fromUnitKey];
        const toUnit = units.temperature[toUnitKey];
        
        // 先转换为摄氏度
        const celsius = (value + fromUnit.offset) / fromUnit.factor;
        // 再从摄氏度转换为目标单位
        result = celsius * toUnit.factor + toUnit.offset;
    } else if (currentType === 'currency') {
        // 货币转换
        const fromRate = units.currency[fromUnitKey].rate;
        const toRate = units.currency[toUnitKey].rate;
        result = (value / fromRate) * toRate;
    } else {
        // 其他单位转换
        const fromFactor = units[currentType][fromUnitKey].factor;
        const toFactor = units[currentType][toUnitKey].factor;
        result = (value * fromFactor) / toFactor;
    }

    toValue.value = result.toFixed(4);
    updateVisualization();
    
    // 添加到历史记录
    addToHistory(value, fromUnitKey, result, toUnitKey);
}

// 添加到历史记录
function addToHistory(fromValue, fromUnit, toValue, toUnit) {
    const historyItem = {
        timestamp: new Date(),
        fromValue,
        fromUnit,
        toValue,
        toUnit,
        type: currentType
    };
    
    conversionHistory.unshift(historyItem);
    if (conversionHistory.length > 10) {
        conversionHistory.pop();
    }
    
    updateHistoryDisplay();
    saveHistory();
}

// 更新历史记录显示
function updateHistoryDisplay() {
    historyList.innerHTML = '';
    conversionHistory.forEach(item => {
        const li = document.createElement('li');
        const fromUnitName = units[item.type][item.fromUnit].name;
        const toUnitName = units[item.type][item.toUnit].name;
        
        li.textContent = `${item.fromValue} ${fromUnitName} = ${item.toValue.toFixed(4)} ${toUnitName}`;
        historyList.appendChild(li);
    });
}

// 保存历史记录到本地存储
function saveHistory() {
    localStorage.setItem('conversionHistory', JSON.stringify(conversionHistory));
}

// 加载历史记录
function loadHistory() {
    const savedHistory = localStorage.getItem('conversionHistory');
    if (savedHistory) {
        conversionHistory = JSON.parse(savedHistory);
        updateHistoryDisplay();
    }
}

// 清除历史记录
clearHistoryBtn.addEventListener('click', () => {
    conversionHistory = [];
    updateHistoryDisplay();
    localStorage.removeItem('conversionHistory');
});

// 事件监听器
typeBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        typeBtns.forEach(b => b.classList.remove('active'));
        btn.classList.add('active');
        currentType = btn.dataset.type;
        initializeUnits(currentType);
        fromValue.value = '';
        toValue.value = '';
        updateVisualization();
    });
});

fromValue.addEventListener('input', convert);
fromUnit.addEventListener('change', convert);
toUnit.addEventListener('change', convert);

swapBtn.addEventListener('click', () => {
    const tempValue = fromValue.value;
    const tempUnit = fromUnit.value;
    
    fromValue.value = toValue.value;
    fromUnit.value = toUnit.value;
    toValue.value = tempValue;
    toUnit.value = tempUnit;
    
    convert();
});

// 获取实时汇率
async function updateCurrencyRates() {
    try {
        const response = await fetch('https://api.exchangerate-api.com/v4/latest/CNY');
        const data = await response.json();
        
        Object.keys(units.currency).forEach(currency => {
            if (currency !== 'CNY') {
                units.currency[currency].rate = data.rates[currency];
            }
        });
        
        // 如果当前正在显示货币转换，更新显示
        if (currentType === 'currency') {
            convert();
        }
    } catch (error) {
        console.error('获取汇率失败:', error);
    }
}

// 每5分钟更新一次汇率
setInterval(updateCurrencyRates, 5 * 60 * 1000);

// 初始化
initializeUnits(currentType);
loadHistory();
updateCurrencyRates();

// 在现有代码的基础上添加新工具的功能

// 工具切换
const toolBtns = document.querySelectorAll('.tool-btn');
const toolSections = document.querySelectorAll('.tool-section');

toolBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const tool = btn.dataset.tool;
        
        toolBtns.forEach(b => b.classList.remove('active'));
        toolSections.forEach(s => s.classList.remove('active'));
        
        btn.classList.add('active');
        document.getElementById(tool).classList.add('active');
    });
});

// 计算器功能
const calcInput = document.getElementById('calcInput');
const calcBtns = document.querySelectorAll('.calc-btn');
let currentCalculation = '';

calcBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const action = btn.dataset.action;
        const value = btn.textContent.trim();

        if (action === 'number') {
            currentCalculation += value;
        } else if (action === 'decimal') {
            // 只允许一个小数点（可根据需要改进为每个数字段允许一个）
            if (!currentCalculation.endsWith('.') && !currentCalculation.split(/\+|\-|×|÷/).pop().includes('.')) {
                currentCalculation += '.';
            }
        } else if (action === 'clear') {
            currentCalculation = '';
        } else if (action === 'backspace') {
            currentCalculation = currentCalculation.slice(0, -1);
        } else if (action === 'percent') {
            try {
                currentCalculation = (parseFloat(currentCalculation) / 100).toString();
            } catch (e) {
                currentCalculation = 'Error';
            }
        } else if (action === 'plusminus') {
            try {
                currentCalculation = (-parseFloat(currentCalculation)).toString();
            } catch (e) {
                currentCalculation = 'Error';
            }
        } else if (["add", "subtract", "multiply", "divide"].includes(action)) {
            // 运算符映射
            const opMap = { add: '+', subtract: '-', multiply: '×', divide: '÷' };
            currentCalculation += opMap[action];
        } else if (action === 'equals') {
            try {
                const calculation = currentCalculation
                    .replace(/×/g, '*')
                    .replace(/÷/g, '/');
                currentCalculation = eval(calculation).toString();
            } catch (e) {
                currentCalculation = 'Error';
            }
        }
        calcInput.value = currentCalculation;
    });
});

// 日期计算器功能
const startDate = document.getElementById('startDate');
const endDate = document.getElementById('endDate');
const daysDiff = document.getElementById('daysDiff');
const workDays = document.getElementById('workDays');
const weeksDiff = document.getElementById('weeksDiff');
const addDaysBtn = document.getElementById('addDays');
const subtractDaysBtn = document.getElementById('subtractDays');

function calculateDateDiff() {
    const start = new Date(startDate.value);
    const end = new Date(endDate.value);
    
    if (start && end && !isNaN(start) && !isNaN(end)) {
        const diffTime = Math.abs(end - start);
        const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
        
        // 计算工作日（简单实现，不考虑节假日）
        let workDaysCount = 0;
        for (let i = 0; i < diffDays; i++) {
            const date = new Date(start);
            date.setDate(date.getDate() + i);
            if (date.getDay() !== 0 && date.getDay() !== 6) {
                workDaysCount++;
            }
        }
        
        daysDiff.textContent = diffDays;
        workDays.textContent = workDaysCount;
        weeksDiff.textContent = Math.floor(diffDays / 7);
    }
}

startDate.addEventListener('change', calculateDateDiff);
endDate.addEventListener('change', calculateDateDiff);

addDaysBtn.addEventListener('click', () => {
    if (endDate.value) {
        const date = new Date(endDate.value);
        date.setDate(date.getDate() + 1);
        endDate.value = date.toISOString().split('T')[0];
        calculateDateDiff();
    }
});

subtractDaysBtn.addEventListener('click', () => {
    if (endDate.value) {
        const date = new Date(endDate.value);
        date.setDate(date.getDate() - 1);
        endDate.value = date.toISOString().split('T')[0];
        calculateDateDiff();
    }
});

// 颜色工具功能
const colorInput = document.getElementById('colorInput');
const hexValue = document.getElementById('hexValue');
const rgbValue = document.getElementById('rgbValue');
const hslValue = document.getElementById('hslValue');
const colorPalette = document.getElementById('colorPalette');

function updateColorValues(color) {
    hexValue.value = color;
    
    // 转换为RGB
    const r = parseInt(color.substr(1,2), 16);
    const g = parseInt(color.substr(3,2), 16);
    const b = parseInt(color.substr(5,2), 16);
    rgbValue.value = `rgb(${r}, ${g}, ${b})`;
    
    // 转换为HSL
    const hsl = rgbToHsl(r, g, b);
    hslValue.value = `hsl(${Math.round(hsl.h)}°, ${Math.round(hsl.s)}%, ${Math.round(hsl.l)}%)`;
    
    // 生成配色方案
    generateColorPalette(color);
}

function rgbToHsl(r, g, b) {
    r /= 255;
    g /= 255;
    b /= 255;
    
    const max = Math.max(r, g, b);
    const min = Math.min(r, g, b);
    let h, s, l = (max + min) / 2;
    
    if (max === min) {
        h = s = 0;
    } else {
        const d = max - min;
        s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
        
        switch (max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        
        h /= 6;
    }
    
    return { h: h * 360, s: s * 100, l: l * 100 };
}

function generateColorPalette(baseColor) {
    const colors = [
        baseColor,
        adjustColor(baseColor, 30),
        adjustColor(baseColor, -30),
        adjustColor(baseColor, 60),
        adjustColor(baseColor, -60)
    ];
    
    colorPalette.innerHTML = '';
    colors.forEach(color => {
        const div = document.createElement('div');
        div.className = 'palette-color';
        div.style.backgroundColor = color;
        div.addEventListener('click', () => {
            colorInput.value = color;
            updateColorValues(color);
        });
        colorPalette.appendChild(div);
    });
}

function adjustColor(color, amount) {
    const r = parseInt(color.substr(1,2), 16);
    const g = parseInt(color.substr(3,2), 16);
    const b = parseInt(color.substr(5,2), 16);
    
    const hsl = rgbToHsl(r, g, b);
    hsl.h = (hsl.h + amount) % 360;
    
    return hslToRgb(hsl.h, hsl.s, hsl.l);
}

function hslToRgb(h, s, l) {
    h /= 360;
    s /= 100;
    l /= 100;
    
    let r, g, b;
    
    if (s === 0) {
        r = g = b = l;
    } else {
        const hue2rgb = (p, q, t) => {
            if (t < 0) t += 1;
            if (t > 1) t -= 1;
            if (t < 1/6) return p + (q - p) * 6 * t;
            if (t < 1/2) return q;
            if (t < 2/3) return p + (q - p) * (2/3 - t) * 6;
            return p;
        };
        
        const q = l < 0.5 ? l * (1 + s) : l + s - l * s;
        const p = 2 * l - q;
        
        r = hue2rgb(p, q, h + 1/3);
        g = hue2rgb(p, q, h);
        b = hue2rgb(p, q, h - 1/3);
    }
    
    const toHex = x => {
        const hex = Math.round(x * 255).toString(16);
        return hex.length === 1 ? '0' + hex : hex;
    };
    
    return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
}

colorInput.addEventListener('input', (e) => {
    updateColorValues(e.target.value);
});

// 文本工具功能
const textInput = document.getElementById('textInput');
const textBtns = document.querySelectorAll('.text-btn');
const charCount = document.getElementById('charCount');
const wordCount = document.getElementById('wordCount');
const lineCount = document.getElementById('lineCount');

function updateTextStats() {
    const text = textInput.value;
    charCount.textContent = text.length;
    wordCount.textContent = text.trim() ? text.trim().split(/\s+/).length : 0;
    lineCount.textContent = text ? text.split('\n').length : 0;
}

textBtns.forEach(btn => {
    btn.addEventListener('click', () => {
        const action = btn.dataset.action;
        const text = textInput.value;
        
        switch(action) {
            case 'uppercase':
                textInput.value = text.toUpperCase();
                break;
            case 'lowercase':
                textInput.value = text.toLowerCase();
                break;
            case 'capitalize':
                textInput.value = text.split(' ').map(word => 
                    word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
                ).join(' ');
                break;
            case 'reverse':
                textInput.value = text.split('').reverse().join('');
                break;
            case 'count':
                updateTextStats();
                break;
            case 'clear':
                textInput.value = '';
                break;
        }
        
        updateTextStats();
    });
});

textInput.addEventListener('input', updateTextStats);

// 初始化
updateColorValues(colorInput.value);
updateTextStats();

// AI 聊天功能
const chatMessages = document.querySelector('.chat-messages');
const chatInput = document.querySelector('#aiInput');
const sendBtn = document.querySelector('#sendMessage');
const clearChatBtn = document.querySelector('[data-action="clear-chat"]');
const copyLastBtn = document.querySelector('[data-action="copy-last"]');

// 思考动画
function showThinking() {
    const old = chatMessages.querySelector('.ai-thinking');
    if (old) old.remove();
    const thinkingDiv = document.createElement('div');
    thinkingDiv.className = 'ai-thinking';
    thinkingDiv.innerHTML = `
        <i class="fas fa-robot"></i>
        <span>思考中</span>
        <span class="ai-thinking-dots">
            <span></span><span></span><span></span>
        </span>
    `;
    chatMessages.appendChild(thinkingDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}
function removeThinking() {
    const old = chatMessages.querySelector('.ai-thinking');
    if (old) old.remove();
}

// 初始化欢迎消息
function initChat() {
    chatMessages.innerHTML = '';
    const welcomeMessage = {
        type: 'system',
        content: '您好！我是 AI 助手，请问有什么可以帮您？'
    };
    addMessage(welcomeMessage);
}

// Markdown渲染函数
function renderMarkdown(text) {
    // 去除 Markdown 标题（#、##、###等）
    text = text.replace(/^#+\s.*$(\r?\n)?/gm, '');
    // 代码块
    text = text.replace(/```([\s\S]*?)```/g, '<pre class="ai-code">$1</pre>');
    // 行内代码
    text = text.replace(/`([^`]+)`/g, '<code class="ai-inline">$1</code>');
    // 粗体
    text = text.replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>');
    // 斜体
    text = text.replace(/\*([^*]+)\*/g, '<i>$1</i>');
    // 换行
    text = text.replace(/\n/g, '<br>');
    // 列表
    text = text.replace(/(^|<br>)[\-\*] (.+?)(?=<br>|$)/g, '$1<li>$2</li>');
    // 包裹ul
    text = text.replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>');
    return text;
}

// 美化后的addMessage
function addMessage(message) {
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${message.type}`;
    const icon = message.type === 'system' ? 'fa-robot' : 'fa-user';
    let content = message.content;
    if (message.type === 'system') {
        content = renderMarkdown(content);
    } else {
        content = content.replace(/\n/g, '<br>');
    }
    messageDiv.innerHTML = `
        <div class="message-content">
            <i class="fas ${icon}"></i>
            <div class="ai-message-text">${content}</div>
        </div>
    `;
    chatMessages.appendChild(messageDiv);
    chatMessages.scrollTop = chatMessages.scrollHeight;
}

// 发送消息
async function sendMessage() {
    const message = chatInput.value.trim();
    if (!message) return;

    addMessage({ type: 'user', content: message });
    chatInput.value = '';

    showThinking(); // 显示思考动画

    try {
        const options = {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer sk-jsdalovkbolrevgqmjywwdoxwucagsnhshuotgpdqfirxrte',
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                model: 'Qwen/QwQ-32B',
                messages: [{ role: 'user', content: message }],
                stream: false,
                max_tokens: 4096,
                thinking_budget: 4096,
                min_p: 0.05,
                stop: null,
                temperature: 0.7,
                top_p: 0.7,
                top_k: 50,
                frequency_penalty: 0.5,
                n: 1,
                response_format: { type: 'text' }
            })
        };

        const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', options);
        const text = await response.text();
        let data;
        try {
            data = JSON.parse(text);
        } catch {
            data = { error: { message: text } };
        }

        removeThinking(); // 移除思考动画

        if (response.status !== 200) {
            addMessage({
                type: 'system',
                content: 'API错误: ' + (data.error?.message || text)
            });
            return;
        }

        if (data && data.choices && data.choices[0] && data.choices[0].message && data.choices[0].message.content) {
            addMessage({
                type: 'system',
                content: data.choices[0].message.content
            });
        } else {
            addMessage({
                type: 'system',
                content: 'AI无回复或接口异常。'
            });
        }
    } catch (error) {
        removeThinking(); // 移除思考动画
        console.error('Error:', error);
        addMessage({
            type: 'system',
            content: '抱歉，AI接口请求失败。'
        });
    }
}

// 清空聊天记录
function clearChat() {
    initChat();
}

// 复制最后一条消息
function copyLastMessage() {
    const messages = chatMessages.querySelectorAll('.message');
    if (messages.length > 0) {
        const lastMessage = messages[messages.length - 1].querySelector('p').textContent;
        navigator.clipboard.writeText(lastMessage)
            .then(() => {
                alert('已复制到剪贴板！');
            })
            .catch(err => {
                console.error('复制失败:', err);
            });
    }
}

// 事件监听
if (sendBtn) sendBtn.addEventListener('click', sendMessage);
if (chatInput) chatInput.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
    }
});
if (clearChatBtn) clearChatBtn.addEventListener('click', clearChat);
if (copyLastBtn) copyLastBtn.addEventListener('click', copyLastMessage);

// 初始化
initChat();

// 翻译功能
const sourceText = document.querySelector('#sourceText');
const targetText = document.querySelector('#targetText');
const sourceLang = document.querySelector('#sourceLang');
const targetLang = document.querySelector('#targetLang');
const translateBtn = document.querySelector('.translate-btn');
const swapLangBtn = document.querySelector('.swap-lang-btn');
const clearTextBtn = document.querySelector('.clear-text-btn');
const copyTranslationBtn = document.querySelector('.copy-translation-btn');
const translationHistory = document.querySelector('#translationHistory');

// 支持的语言列表
const languages = {
    'zh': '中文',
    'en': '英语',
    'ja': '日语',
    'ko': '韩语',
    'fr': '法语',
    'de': '德语',
    'es': '西班牙语',
    'ru': '俄语',
    'pt': '葡萄牙语',
    'it': '意大利语',
    'nl': '荷兰语',
    'pl': '波兰语',
    'tr': '土耳其语',
    'ar': '阿拉伯语',
    'hi': '印地语',
    'th': '泰语',
    'vi': '越南语'
};

// 初始化语言选择器
function initLanguageSelectors() {
    sourceLang.innerHTML = '';
    targetLang.innerHTML = '';
    
    for (const [code, name] of Object.entries(languages)) {
        sourceLang.innerHTML += `<option value="${code}">${name}</option>`;
        targetLang.innerHTML += `<option value="${code}">${name}</option>`;
    }
    
    // 设置默认语言
    sourceLang.value = 'zh';
    targetLang.value = 'en';
}

// 翻译文本
async function translateText() {
    const text = sourceText.value.trim();
    if (!text) return;
    
    try {
        showThinking(); // 显示加载动画
        
        const response = await fetch('https://api.siliconflow.cn/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer sk-jsdalovkbolrevgqmjywwdoxwucagsnhshuotgpdqfirxrte'
            },
            body: JSON.stringify({
                model: 'Qwen/QwQ-32B',
                messages: [{
                    role: 'user',
                    content: `请将以下${languages[sourceLang.value]}文本翻译成${languages[targetLang.value]}：\n\n${text}`
                }],
                temperature: 0.3,
                max_tokens: 2000
            })
        });

        const data = await response.json();
        removeThinking(); // 移除加载动画

        if (data.choices && data.choices[0] && data.choices[0].message) {
            const translatedText = data.choices[0].message.content.trim();
            targetText.value = translatedText;
            
            // 添加到历史记录
            addToHistory(text, translatedText);
        } else {
            throw new Error('翻译失败');
        }
    } catch (error) {
        removeThinking(); // 移除加载动画
        console.error('Translation error:', error);
        alert('翻译失败，请稍后重试。');
    }
}

// 交换语言
function swapLanguages() {
    const tempLang = sourceLang.value;
    sourceLang.value = targetLang.value;
    targetLang.value = tempLang;
    
    const tempText = sourceText.value;
    sourceText.value = targetText.value;
    targetText.value = tempText;
}

// 清空文本
function clearText() {
    sourceText.value = '';
    targetText.value = '';
}

// 复制翻译结果
function copyTranslation() {
    if (targetText.value) {
        navigator.clipboard.writeText(targetText.value)
            .then(() => {
                const copyBtn = copyTranslationBtn;
                const originalText = copyBtn.innerHTML;
                copyBtn.innerHTML = '<i class="fas fa-check"></i>';
                setTimeout(() => {
                    copyBtn.innerHTML = originalText;
                }, 2000);
            })
            .catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制。');
            });
    }
}

// 添加到历史记录
function addToHistory(source, target) {
    const li = document.createElement('li');
    li.innerHTML = `
        <div class="history-item">
            <div class="history-languages">
                <span>${languages[sourceLang.value]} → ${languages[targetLang.value]}</span>
                <span class="history-time">${new Date().toLocaleTimeString()}</span>
            </div>
            <div class="history-text">
                <p class="source-text">${source}</p>
                <p class="target-text">${target}</p>
            </div>
            <div class="history-actions">
                <button class="option-btn" onclick="useTranslation(this)" title="重新翻译">
                    <i class="fas fa-redo"></i>
                </button>
                <button class="option-btn" onclick="copyHistoryText(this)" title="复制译文">
                    <i class="fas fa-copy"></i>
                </button>
            </div>
        </div>
    `;
    
    translationHistory.insertBefore(li, translationHistory.firstChild);
    
    // 限制历史记录数量
    if (translationHistory.children.length > 10) {
        translationHistory.removeChild(translationHistory.lastChild);
    }
    
    // 保存到本地存储
    saveTranslationHistory();
}

// 使用历史翻译
function useTranslation(button) {
    const li = button.closest('.history-item');
    const source = li.querySelector('.source-text').textContent;
    sourceText.value = source;
    translateText();
}

// 复制历史记录中的文本
function copyHistoryText(button) {
    const li = button.closest('.history-item');
    const text = li.querySelector('.target-text').textContent;
    
    navigator.clipboard.writeText(text)
        .then(() => {
            const originalHTML = button.innerHTML;
            button.innerHTML = '<i class="fas fa-check"></i>';
            setTimeout(() => {
                button.innerHTML = originalHTML;
            }, 2000);
        })
        .catch(err => {
            console.error('复制失败:', err);
            alert('复制失败，请手动复制。');
        });
}

// 保存翻译历史到本地存储
function saveTranslationHistory() {
    const history = Array.from(translationHistory.children).map(li => ({
        sourceLang: sourceLang.value,
        targetLang: targetLang.value,
        source: li.querySelector('.source-text').textContent,
        target: li.querySelector('.target-text').textContent,
        time: li.querySelector('.history-time').textContent
    }));
    
    localStorage.setItem('translationHistory', JSON.stringify(history));
}

// 加载翻译历史
function loadTranslationHistory() {
    const savedHistory = localStorage.getItem('translationHistory');
    if (savedHistory) {
        const history = JSON.parse(savedHistory);
        history.forEach(item => {
            const li = document.createElement('li');
            li.innerHTML = `
                <div class="history-item">
                    <div class="history-languages">
                        <span>${languages[item.sourceLang]} → ${languages[item.targetLang]}</span>
                        <span class="history-time">${item.time}</span>
                    </div>
                    <div class="history-text">
                        <p class="source-text">${item.source}</p>
                        <p class="target-text">${item.target}</p>
                    </div>
                    <div class="history-actions">
                        <button class="option-btn" onclick="useTranslation(this)" title="重新翻译">
                            <i class="fas fa-redo"></i>
                        </button>
                        <button class="option-btn" onclick="copyHistoryText(this)" title="复制译文">
                            <i class="fas fa-copy"></i>
                        </button>
                    </div>
                </div>
            `;
            translationHistory.appendChild(li);
        });
    }
}

// 事件监听
translateBtn.addEventListener('click', translateText);
swapLangBtn.addEventListener('click', swapLanguages);
clearTextBtn.addEventListener('click', clearText);
copyTranslationBtn.addEventListener('click', copyTranslation);

// 添加自动翻译功能（输入后延迟500ms自动翻译）
let translateTimeout;
sourceText.addEventListener('input', () => {
    clearTimeout(translateTimeout);
    translateTimeout = setTimeout(translateText, 500);
});

// 初始化
document.addEventListener('DOMContentLoaded', () => {
    initLanguageSelectors();
    loadTranslationHistory();

    // 世界时钟功能（可自定义城市）
    window.renderClocks = null;
    const miniClock = document.getElementById('mini-clock');
    if (miniClock) {
        // 默认城市
        const defaultCities = [
            { name: '北京', tz: 'Asia/Shanghai' },
            { name: '纽约', tz: 'America/New_York' },
            { name: '伦敦', tz: 'Europe/London' },
            { name: '东京', tz: 'Asia/Tokyo' },
            { name: '悉尼', tz: 'Australia/Sydney' },
            { name: '巴黎', tz: 'Europe/Paris' },
            { name: '洛杉矶', tz: 'America/Los_Angeles' }
        ];
        // 支持的城市及时区映射
        const cityTzMap = {
            '北京': 'Asia/Shanghai', 'beijing': 'Asia/Shanghai',
            '纽约': 'America/New_York', 'new york': 'America/New_York',
            '伦敦': 'Europe/London', 'london': 'Europe/London',
            '东京': 'Asia/Tokyo', 'tokyo': 'Asia/Tokyo',
            '悉尼': 'Australia/Sydney', 'sydney': 'Australia/Sydney',
            '巴黎': 'Europe/Paris', 'paris': 'Europe/Paris',
            '洛杉矶': 'America/Los_Angeles', 'los angeles': 'America/Los_Angeles',
            '柏林': 'Europe/Berlin', 'berlin': 'Europe/Berlin',
            '莫斯科': 'Europe/Moscow', 'moscow': 'Europe/Moscow',
            '首尔': 'Asia/Seoul', 'seoul': 'Asia/Seoul',
            '香港': 'Asia/Hong_Kong', 'hong kong': 'Asia/Hong_Kong',
            '新加坡': 'Asia/Singapore', 'singapore': 'Asia/Singapore',
            '迪拜': 'Asia/Dubai', 'dubai': 'Asia/Dubai',
            '孟买': 'Asia/Kolkata', 'mumbai': 'Asia/Kolkata',
            '芝加哥': 'America/Chicago', 'chicago': 'America/Chicago',
            '旧金山': 'America/Los_Angeles', 'san francisco': 'America/Los_Angeles'
        };
        function getClockCities() {
            return JSON.parse(localStorage.getItem('clockCities') || 'null') || defaultCities;
        }
        function saveClockCities(list) {
            localStorage.setItem('clockCities', JSON.stringify(list));
        }
        window.renderClocks = function() {
            miniClock.innerHTML = '';
            let cities = getClockCities();
            let validCities = [];
            let html = `<form id="addCityForm" style="display:flex;gap:0.5em;justify-content:center;margin-bottom:1.2em;flex-wrap:wrap;">
                <input type="text" id="cityNameInput" placeholder="城市名(如北京/伦敦/东京)" style="min-width:120px;">
                <button type="submit" class="game-btn" style="padding:0.5em 1.2em;">添加城市</button>
            </form>`;
            html += '<div style="display:flex;flex-wrap:wrap;gap:2.5rem;justify-content:center;">';
            cities.forEach((city, idx) => {
                try {
                    const now = new Date();
                    const time = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', hour12: false, timeZone: city.tz });
                    const date = now.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', timeZone: city.tz });
                    html += `<div style="min-width:120px;text-align:center;background:var(--container-bg);box-shadow:0 2px 8px var(--shadow-color);border-radius:1em;padding:1.2em 1em;position:relative;">
                        <div style="font-weight:600;color:var(--primary-color);font-size:1.1em;margin-bottom:0.3em;">${city.name}</div>
                        <div style="font-size:2em;font-weight:bold;letter-spacing:0.05em;">${time}</div>
                        <div style="color:var(--text-light);font-size:1em;margin-top:0.2em;">${date}</div>
                        <button class="clear-btn clock-del-btn" data-idx="${validCities.length}" title="删除" style="position:absolute;top:0.5em;right:0.5em;padding:0.2em 0.5em;"><i class="fas fa-times"></i></button>
                    </div>`;
                    validCities.push(city);
                } catch (e) {
                    // 跳过无效时区
                }
            });
            html += '</div>';
            miniClock.innerHTML = html;
            saveClockCities(validCities); // 自动清理无效城市

            // 绑定添加城市
            const addCityForm = document.getElementById('addCityForm');
            if (addCityForm) {
                addCityForm.onsubmit = function(e) {
                    e.preventDefault();
                    const name = document.getElementById('cityNameInput').value.trim();
                    if (!name) return;
                    const key = name.toLowerCase();
                    const tz = cityTzMap[name] || cityTzMap[key];
                    if (!tz) {
                        alert('暂不支持该城市，请输入常见城市名');
                        return;
                    }
                    let cities = getClockCities();
                    cities.push({ name, tz });
                    saveClockCities(cities);
                    window.renderClocks();
                };
            }
            // 绑定删除城市
            miniClock.querySelectorAll('.clock-del-btn').forEach(btn => {
                btn.onclick = function() {
                    let idx = +btn.dataset.idx;
                    let cities = getClockCities();
                    cities.splice(idx, 1);
                    saveClockCities(cities);
                    window.renderClocks();
                };
            });
        }
        window.renderClocks();
        setInterval(window.renderClocks, 1000 * 30);
    }

    // 实用工具切换逻辑
    const miniBtns = document.querySelectorAll('.tool-mini-btn');
    const miniTools = document.querySelectorAll('.mini-tool');
    if (miniBtns.length && miniTools.length) {
        miniBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                miniBtns.forEach(b => b.classList.remove('active'));
                miniTools.forEach(t => t.classList.remove('active'));
                btn.classList.add('active');
                const id = 'mini-' + btn.dataset.mini;
                const tool = document.getElementById(id);
                if (tool) tool.classList.add('active');
                // 切换到世界时钟时刷新内容
                if (id === 'mini-clock' && typeof window.renderClocks === 'function') {
                    window.renderClocks();
                }
            });
        });
        // 默认显示第一个
        miniBtns[0].classList.add('active');
        miniTools[0].classList.add('active');
    }

    // 初始化实用工具
    initQRCode();
    initImageCompress();
    initMarkdownEditor();
}); 

// 二维码生成器功能
function initQRCode() {
    const qrcodeText = document.getElementById('qrcodeText');
    const qrcodeSize = document.getElementById('qrcodeSize');
    const qrcodeColor = document.getElementById('qrcodeColor');
    const generateQRCode = document.getElementById('generateQRCode');
    const qrcodeOutput = document.getElementById('qrcodeOutput');
    const downloadQRCode = document.getElementById('downloadQRCode');

    if (!qrcodeText || !qrcodeSize || !qrcodeColor || !generateQRCode || !qrcodeOutput || !downloadQRCode) {
        console.error('QR Code elements not found');
        return;
    }

    let qrcode = null;

    generateQRCode.addEventListener('click', () => {
        const text = qrcodeText.value.trim();
        if (!text) {
            alert('请输入要生成二维码的内容！');
            return;
        }

        try {
            // 清空之前的内容
            qrcodeOutput.innerHTML = '';
            
            // 如果已存在QR实例，先清除
            if (qrcode) {
                qrcode.clear();
            }
            
            // 创建新的QR实例
            qrcode = new QRCode(qrcodeOutput, {
                text: text,
                width: parseInt(qrcodeSize.value),
                height: parseInt(qrcodeSize.value),
                colorDark: qrcodeColor.value,
                colorLight: "#ffffff",
                correctLevel: QRCode.CorrectLevel.H
            });

            // 等待图片生成完成后显示下载按钮
            setTimeout(() => {
                const img = qrcodeOutput.querySelector('img');
                if (img) {
                    downloadQRCode.style.display = 'block';
                } else {
                    console.error('QR Code image not generated');
                    alert('二维码生成失败，请重试！');
                }
            }, 100);

        } catch (error) {
            console.error('Error generating QR code:', error);
            alert('二维码生成失败，请重试！');
        }
    });

    downloadQRCode.addEventListener('click', () => {
        const img = qrcodeOutput.querySelector('img');
        if (img) {
            const link = document.createElement('a');
            link.download = 'qrcode.png';
            link.href = img.src;
            link.click();
        }
    });

    // 添加输入框的回车响应
    qrcodeText.addEventListener('keypress', (e) => {
        if (e.key === 'Enter') {
            generateQRCode.click();
        }
    });
} 

// 实用工具切换逻辑
function initMiniTools() {
    const miniBtns = document.querySelectorAll('.tool-mini-btn');
    const miniTools = document.querySelectorAll('.mini-tool');

    if (!miniBtns.length || !miniTools.length) {
        console.error('Mini tools elements not found');
        return;
    }

    miniBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            // 移除所有活动状态
            miniBtns.forEach(b => b.classList.remove('active'));
            // 隐藏所有工具
            miniTools.forEach(t => t.style.display = 'none');
            // 激活当前按钮
            btn.classList.add('active');
            // 显示对应的工具
            const id = 'mini-' + btn.dataset.mini;
            const tool = document.getElementById(id);
            if (tool) {
                tool.style.display = 'block';
                // 切换到世界时钟时刷新内容
                if (id === 'mini-clock' && typeof window.renderClocks === 'function') {
                    window.renderClocks();
                }
            }
        });
    });

    // 默认显示第一个工具
    if (miniBtns[0]) {
        miniBtns[0].click();
    }
}

// 页面加载完成后初始化所有工具
document.addEventListener('DOMContentLoaded', () => {
    // 初始化工具切换
    initMiniTools();
    // 初始化二维码生成器
    initQRCode();
    // 初始化图片压缩工具
    initImageCompress();
    // 初始化Markdown预览工具
    initMarkdownEditor();
}); 

// 图片压缩功能
function initImageCompress() {
    const imgDropZone = document.getElementById('imgDropZone');
    const imgInput = document.getElementById('imgInput');
    const qualitySlider = document.getElementById('qualitySlider');
    const qualityValue = document.getElementById('qualityValue');
    const maxWidth = document.getElementById('maxWidth');
    const maxHeight = document.getElementById('maxHeight');
    const originalPreview = document.getElementById('originalPreview');
    const compressedPreview = document.getElementById('compressedPreview');
    const originalInfo = document.getElementById('originalInfo');
    const compressedInfo = document.getElementById('compressedInfo');
    const downloadCompressed = document.getElementById('downloadCompressed');

    if (!imgDropZone || !imgInput || !qualitySlider || !qualityValue || !maxWidth || !maxHeight || 
        !originalPreview || !compressedPreview || !originalInfo || !compressedInfo || !downloadCompressed) {
        console.error('Image compress elements not found');
        return;
    }

    // 更新质量显示
    qualitySlider.addEventListener('input', () => {
        qualityValue.textContent = qualitySlider.value + '%';
        if (originalPreview.src) {
            compressImage();
        }
    });

    // 尺寸改变时重新压缩
    maxWidth.addEventListener('change', () => originalPreview.src && compressImage());
    maxHeight.addEventListener('change', () => originalPreview.src && compressImage());

    // 处理文件拖放
    imgDropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        imgDropZone.style.borderColor = 'var(--primary-color)';
    });

    imgDropZone.addEventListener('dragleave', () => {
        imgDropZone.style.borderColor = 'var(--border-color)';
    });

    imgDropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        imgDropZone.style.borderColor = 'var(--border-color)';
        const file = e.dataTransfer.files[0];
        if (file && file.type.startsWith('image/')) {
            handleImageFile(file);
        }
    });

    // 点击上传
    imgDropZone.addEventListener('click', () => imgInput.click());
    imgInput.addEventListener('change', () => {
        const file = imgInput.files[0];
        if (file) {
            handleImageFile(file);
        }
    });

    function handleImageFile(file) {
        const reader = new FileReader();
        reader.onload = (e) => {
            originalPreview.src = e.target.result;
            originalPreview.onload = () => {
                updateImageInfo(originalPreview, file.size, originalInfo);
                compressImage();
            };
        };
        reader.readAsDataURL(file);
    }

    function compressImage() {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        
        // 计算新尺寸
        let width = originalPreview.naturalWidth;
        let height = originalPreview.naturalHeight;
        const maxW = parseInt(maxWidth.value) || width;
        const maxH = parseInt(maxHeight.value) || height;
        
        if (width > maxW) {
            height = (height * maxW) / width;
            width = maxW;
        }
        if (height > maxH) {
            width = (width * maxH) / height;
            height = maxH;
        }
        
        canvas.width = width;
        canvas.height = height;
        
        // 绘制并压缩图片
        ctx.drawImage(originalPreview, 0, 0, width, height);
        const quality = parseInt(qualitySlider.value) / 100;
        const compressedDataUrl = canvas.toDataURL('image/jpeg', quality);
        
        // 显示压缩后的图片
        compressedPreview.src = compressedDataUrl;
        compressedPreview.onload = () => {
            // 计算压缩后的大小
            const compressedSize = Math.round((compressedDataUrl.length - 'data:image/jpeg;base64,'.length) * 0.75);
            updateImageInfo(compressedPreview, compressedSize, compressedInfo);
            downloadCompressed.style.display = 'block';
        };
    }

    function updateImageInfo(img, size, infoElement) {
        const sizeText = size < 1024 * 1024 ? 
            Math.round(size / 1024) + ' KB' : 
            (size / (1024 * 1024)).toFixed(2) + ' MB';
        infoElement.textContent = `${img.naturalWidth} x ${img.naturalHeight} | ${sizeText}`;
    }

    // 下载压缩后的图片
    downloadCompressed.addEventListener('click', () => {
        const link = document.createElement('a');
        link.download = 'compressed_image.jpg';
        link.href = compressedPreview.src;
        link.click();
    });
}

// Markdown编辑器功能
function initMarkdownEditor() {
    const markdownInput = document.getElementById('markdownInput');
    const markdownPreview = document.getElementById('markdownPreview');
    const toolbarButtons = document.querySelectorAll('.editor-toolbar .tool-btn');

    if (!markdownInput || !markdownPreview || !toolbarButtons.length) {
        console.error('Markdown editor elements not found');
        return;
    }

    // 实时预览
    markdownInput.addEventListener('input', () => {
        const markdown = markdownInput.value;
        markdownPreview.innerHTML = renderMarkdown(markdown);
    });

    // 工具栏功能
    toolbarButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            const action = btn.dataset.action;
            const start = markdownInput.selectionStart;
            const end = markdownInput.selectionEnd;
            const text = markdownInput.value;
            let result = '';

            switch (action) {
                case 'bold':
                    result = insertMarkdown(text, start, end, '**', '**');
                    break;
                case 'italic':
                    result = insertMarkdown(text, start, end, '*', '*');
                    break;
                case 'heading':
                    result = insertMarkdown(text, start, end, '## ', '');
                    break;
                case 'link':
                    const url = prompt('请输入链接地址：', 'https://');
                    if (url) {
                        result = insertMarkdown(text, start, end, '[', `](${url})`);
                    }
                    break;
                case 'list':
                    result = insertMarkdown(text, start, end, '- ', '');
                    break;
                case 'code':
                    result = insertMarkdown(text, start, end, '`', '`');
                    break;
                case 'preview':
                    markdownPreview.classList.toggle('fullscreen');
                    break;
            }

            if (result) {
                markdownInput.value = result.text;
                markdownInput.focus();
                markdownInput.setSelectionRange(result.start, result.end);
                markdownInput.dispatchEvent(new Event('input'));
            }
        });
    });
}

// Markdown工具函数
function insertMarkdown(text, start, end, prefix, suffix) {
    const selection = text.substring(start, end);
    const before = text.substring(0, start);
    const after = text.substring(end);
    const newText = before + prefix + selection + suffix + after;
    return {
        text: newText,
        start: start + prefix.length,
        end: end + prefix.length
    };
}

function renderMarkdown(text) {
    // 简单的Markdown渲染实现
    return text
        .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
        .replace(/\*(.*?)\*/g, '<em>$1</em>')
        .replace(/`(.*?)`/g, '<code>$1</code>')
        .replace(/^## (.*$)/gm, '<h2>$1</h2>')
        .replace(/^# (.*$)/gm, '<h1>$1</h1>')
        .replace(/\[(.*?)\]\((.*?)\)/g, '<a href="$2">$1</a>')
        .replace(/^- (.*$)/gm, '<li>$1</li>')
        .replace(/<li>.*<\/li>/g, match => `<ul>${match}</ul>`)
        .split('\n').join('<br>');
}

// 计时器功能
function initTimer() {
    const timerContainer = document.getElementById('mini-timer');
    if (!timerContainer) {
        console.error('Timer container not found');
        return;
    }

    const modeBtns = timerContainer.querySelectorAll('.mode-btn');
    const countdownSection = timerContainer.querySelector('.countdown-section');
    const stopwatchSection = timerContainer.querySelector('.stopwatch-section');
    
    // 倒计时元素
    const hoursInput = document.getElementById('hours');
    const minutesInput = document.getElementById('minutes');
    const secondsInput = document.getElementById('seconds');
    const countdownDisplay = countdownSection.querySelector('.timer-display');
    const countdownStartBtn = countdownSection.querySelector('.start-btn');
    const countdownPauseBtn = countdownSection.querySelector('.pause-btn');
    const countdownResetBtn = countdownSection.querySelector('.reset-btn');

    // 秒表元素
    const stopwatchDisplay = stopwatchSection.querySelector('.timer-display');
    const lapTimesContainer = stopwatchSection.querySelector('.lap-times');
    const stopwatchStartBtn = stopwatchSection.querySelector('.start-btn');
    const stopwatchPauseBtn = stopwatchSection.querySelector('.pause-btn');
    const stopwatchLapBtn = stopwatchSection.querySelector('.lap-btn');
    const stopwatchResetBtn = stopwatchSection.querySelector('.reset-btn');

    let countdownInterval = null;
    let stopwatchInterval = null;
    let countdownTimeLeft = 0;
    let stopwatchTime = 0;
    let lapCount = 0;

    // 模式切换
    modeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            modeBtns.forEach(b => b.classList.remove('active'));
            btn.classList.add('active');
            if (btn.dataset.mode === 'countdown') {
                countdownSection.style.display = 'block';
                stopwatchSection.style.display = 'none';
            } else {
                countdownSection.style.display = 'none';
                stopwatchSection.style.display = 'block';
            }
        });
    });

    // 格式化时间显示
    function formatTime(totalSeconds) {
        const hours = Math.floor(totalSeconds / 3600);
        const minutes = Math.floor((totalSeconds % 3600) / 60);
        const seconds = totalSeconds % 60;
        return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
    }

    // 倒计时功能
    function startCountdown() {
        if (countdownInterval) return;
        
        const hours = parseInt(hoursInput.value) || 0;
        const minutes = parseInt(minutesInput.value) || 0;
        const seconds = parseInt(secondsInput.value) || 0;
        
        countdownTimeLeft = hours * 3600 + minutes * 60 + seconds;
        
        if (countdownTimeLeft <= 0) {
            alert('请设置倒计时时间！');
            return;
        }

        countdownStartBtn.style.display = 'none';
        countdownPauseBtn.style.display = 'inline-flex';

        countdownInterval = setInterval(() => {
            countdownTimeLeft--;
            countdownDisplay.textContent = formatTime(countdownTimeLeft);
            
            if (countdownTimeLeft <= 0) {
                clearInterval(countdownInterval);
                countdownInterval = null;
                alert('倒计时结束！');
                resetCountdown();
            }
        }, 1000);
    }

    function pauseCountdown() {
        clearInterval(countdownInterval);
        countdownInterval = null;
        countdownStartBtn.style.display = 'inline-flex';
        countdownPauseBtn.style.display = 'none';
    }

    function resetCountdown() {
        clearInterval(countdownInterval);
        countdownInterval = null;
        countdownTimeLeft = 0;
        countdownDisplay.textContent = '00:00:00';
        hoursInput.value = '0';
        minutesInput.value = '0';
        secondsInput.value = '0';
        countdownStartBtn.style.display = 'inline-flex';
        countdownPauseBtn.style.display = 'none';
    }

    // 秒表功能
    function startStopwatch() {
        if (stopwatchInterval) return;
        
        stopwatchStartBtn.style.display = 'none';
        stopwatchPauseBtn.style.display = 'inline-flex';

        stopwatchInterval = setInterval(() => {
            stopwatchTime++;
            stopwatchDisplay.textContent = formatTime(stopwatchTime);
        }, 1000);
    }

    function pauseStopwatch() {
        clearInterval(stopwatchInterval);
        stopwatchInterval = null;
        stopwatchStartBtn.style.display = 'inline-flex';
        stopwatchPauseBtn.style.display = 'none';
    }

    function resetStopwatch() {
        clearInterval(stopwatchInterval);
        stopwatchInterval = null;
        stopwatchTime = 0;
        lapCount = 0;
        stopwatchDisplay.textContent = '00:00:00';
        lapTimesContainer.innerHTML = '';
        stopwatchStartBtn.style.display = 'inline-flex';
        stopwatchPauseBtn.style.display = 'none';
    }

    function addLap() {
        if (!stopwatchInterval) return;
        
        lapCount++;
        const lapItem = document.createElement('div');
        lapItem.className = 'lap-item';
        lapItem.innerHTML = `
            <span class="lap-number">计次 ${lapCount}</span>
            <span class="lap-time">${formatTime(stopwatchTime)}</span>
        `;
        lapTimesContainer.insertBefore(lapItem, lapTimesContainer.firstChild);
    }

    // 事件监听
    countdownStartBtn.addEventListener('click', startCountdown);
    countdownPauseBtn.addEventListener('click', pauseCountdown);
    countdownResetBtn.addEventListener('click', resetCountdown);

    stopwatchStartBtn.addEventListener('click', startStopwatch);
    stopwatchPauseBtn.addEventListener('click', pauseStopwatch);
    stopwatchResetBtn.addEventListener('click', resetStopwatch);
    stopwatchLapBtn.addEventListener('click', addLap);

    // 输入限制
    [hoursInput, minutesInput, secondsInput].forEach(input => {
        input.addEventListener('input', () => {
            let value = parseInt(input.value) || 0;
            const max = parseInt(input.max);
            if (value > max) value = max;
            if (value < 0) value = 0;
            input.value = value;
        });
    });
}

// 初始化所有工具
document.addEventListener('DOMContentLoaded', () => {
    // 初始化工具切换
    initMiniTools();
    // 初始化计时器
    initTimer();
    // 初始化图片压缩工具
    initImageCompress();
    // 初始化Markdown预览工具
    initMarkdownEditor();
}); 

// 游戏相关代码
document.addEventListener('DOMContentLoaded', function() {
    const gameButtons = document.querySelectorAll('.game-btn');
    const gameContainer = document.getElementById('gameContainer');
    
    gameButtons.forEach(button => {
        button.addEventListener('click', function() {
            const gameType = this.getAttribute('data-game');
            gameButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            // 清空游戏容器
            gameContainer.innerHTML = '';
            
            // 根据游戏类型初始化不同的游戏
            switch(gameType) {
                case 'snake':
                    initSnakeGame();
                    break;
                case '2048':
                    init2048Game();
                    break;
                case 'tetris':
                    initTetrisGame();
                    break;
            }
        });
    });
});

// 贪吃蛇游戏
function initSnakeGame() {
    const gameContainer = document.getElementById('gameContainer');
    gameContainer.innerHTML = `
        <div class="game-wrapper">
            <canvas id="snakeCanvas" width="400" height="400"></canvas>
            <div class="game-controls">
                <button id="startSnake">开始游戏</button>
                <div class="score">分数: <span id="snakeScore">0</span></div>
            </div>
        </div>
    `;

    const canvas = document.getElementById('snakeCanvas');
    const ctx = canvas.getContext('2d');
    const startBtn = document.getElementById('startSnake');
    const scoreElement = document.getElementById('snakeScore');

    const gridSize = 20;
    const tileCount = canvas.width / gridSize;
    let snake = [];
    let food = {};
    let dx = gridSize;
    let dy = 0;
    let score = 0;
    let gameLoop = null;
    let gameSpeed = 150;

    function initGame() {
        snake = [
            { x: 5 * gridSize, y: 5 * gridSize }
        ];
        generateFood();
        score = 0;
        scoreElement.textContent = score;
        dx = gridSize;
        dy = 0;
    }

    function generateFood() {
        food = {
            x: Math.floor(Math.random() * tileCount) * gridSize,
            y: Math.floor(Math.random() * tileCount) * gridSize
        };
        // 确保食物不会生成在蛇身上
        for (let segment of snake) {
            if (segment.x === food.x && segment.y === food.y) {
                generateFood();
                break;
            }
        }
    }

    function drawGame() {
        // 清空画布
        ctx.fillStyle = '#f0f0f0';
        ctx.fillRect(0, 0, canvas.width, canvas.height);

        // 绘制食物
        ctx.fillStyle = '#ff0000';
        ctx.fillRect(food.x, food.y, gridSize - 2, gridSize - 2);

        // 绘制蛇
        snake.forEach((segment, index) => {
            ctx.fillStyle = index === 0 ? '#006400' : '#008000';
            ctx.fillRect(segment.x, segment.y, gridSize - 2, gridSize - 2);
        });
    }

    function moveSnake() {
        const head = { x: snake[0].x + dx, y: snake[0].y + dy };

        // 检查是否撞墙
        if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
            gameOver();
            return;
        }

        // 检查是否撞到自己
        for (let segment of snake) {
            if (head.x === segment.x && head.y === segment.y) {
                gameOver();
                return;
            }
        }

        snake.unshift(head);

        // 检查是否吃到食物
        if (head.x === food.x && head.y === food.y) {
            score += 10;
            scoreElement.textContent = score;
            generateFood();
            // 加快游戏速度
            if (gameSpeed > 50) {
                gameSpeed -= 5;
                clearInterval(gameLoop);
                gameLoop = setInterval(gameStep, gameSpeed);
            }
        } else {
            snake.pop();
        }
    }

    function gameStep() {
        moveSnake();
        drawGame();
    }

    function gameOver() {
        clearInterval(gameLoop);
        alert(`游戏结束！得分：${score}`);
        startBtn.textContent = '重新开始';
        startBtn.disabled = false;
    }

    function startGame() {
        if (gameLoop) {
            clearInterval(gameLoop);
        }
        initGame();
        gameSpeed = 150;
        gameLoop = setInterval(gameStep, gameSpeed);
        startBtn.textContent = '游戏中...';
        startBtn.disabled = true;
    }

    // 键盘控制
    document.addEventListener('keydown', (e) => {
        switch (e.key) {
            case 'ArrowUp':
                if (dy === 0) {
                    dx = 0;
                    dy = -gridSize;
                }
                break;
            case 'ArrowDown':
                if (dy === 0) {
                    dx = 0;
                    dy = gridSize;
                }
                break;
            case 'ArrowLeft':
                if (dx === 0) {
                    dx = -gridSize;
                    dy = 0;
                }
                break;
            case 'ArrowRight':
                if (dx === 0) {
                    dx = gridSize;
                    dy = 0;
                }
                break;
        }
    });

    startBtn.addEventListener('click', startGame);
}

// 2048游戏
function init2048Game() {
    const gameContainer = document.getElementById('gameContainer');
    gameContainer.innerHTML = `
        <div class="game-wrapper">
            <div id="game2048" class="game-2048"></div>
            <div class="game-controls">
                <button id="newGame2048">新游戏</button>
                <div class="score">分数: <span id="score2048">0</span></div>
            </div>
        </div>
    `;

    const gameBoard = document.getElementById('game2048');
    const scoreElement = document.getElementById('score2048');
    const newGameBtn = document.getElementById('newGame2048');

    const size = 4;
    let board = [];
    let score = 0;
    let gameOver = false;

    // 初始化游戏板
    function initBoard() {
        board = Array(size).fill().map(() => Array(size).fill(0));
        score = 0;
        gameOver = false;
        scoreElement.textContent = score;
        addNewTile();
        addNewTile();
        renderBoard();
    }

    // 添加新方块
    function addNewTile() {
        const emptyCells = [];
        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                if (board[i][j] === 0) {
                    emptyCells.push({x: i, y: j});
                }
            }
        }
        if (emptyCells.length > 0) {
            const randomCell = emptyCells[Math.floor(Math.random() * emptyCells.length)];
            board[randomCell.x][randomCell.y] = Math.random() < 0.9 ? 2 : 4;
        }
    }

    // 渲染游戏板
    function renderBoard() {
        gameBoard.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
        gameBoard.innerHTML = '';
        
        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                const tile = document.createElement('div');
                tile.className = 'tile';
                const value = board[i][j];
                if (value !== 0) {
                    tile.textContent = value;
                    tile.style.backgroundColor = getTileColor(value);
                    tile.style.color = value <= 4 ? '#776e65' : '#f9f6f2';
                }
                gameBoard.appendChild(tile);
            }
        }
    }

    // 获取方块颜色
    function getTileColor(value) {
        const colors = {
            2: '#eee4da',
            4: '#ede0c8',
            8: '#f2b179',
            16: '#f59563',
            32: '#f67c5f',
            64: '#f65e3b',
            128: '#edcf72',
            256: '#edcc61',
            512: '#edc850',
            1024: '#edc53f',
            2048: '#edc22e'
        };
        return colors[value] || '#cdc1b4';
    }

    // 移动方块
    function move(direction) {
        if (gameOver) return;

        let moved = false;
        const oldBoard = JSON.stringify(board);

        switch(direction) {
            case 'up':
                moved = moveUp();
                break;
            case 'down':
                moved = moveDown();
                break;
            case 'left':
                moved = moveLeft();
                break;
            case 'right':
                moved = moveRight();
                break;
        }

        if (moved) {
            addNewTile();
            renderBoard();
            checkGameOver();
        }
    }

    // 向上移动
    function moveUp() {
        let moved = false;
        for (let j = 0; j < size; j++) {
            for (let i = 1; i < size; i++) {
                if (board[i][j] !== 0) {
                    let row = i;
                    while (row > 0) {
                        if (board[row-1][j] === 0) {
                            board[row-1][j] = board[row][j];
                            board[row][j] = 0;
                            row--;
                            moved = true;
                        } else if (board[row-1][j] === board[row][j]) {
                            board[row-1][j] *= 2;
                            score += board[row-1][j];
                            board[row][j] = 0;
                            moved = true;
                            break;
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        scoreElement.textContent = score;
        return moved;
    }

    // 向下移动
    function moveDown() {
        let moved = false;
        for (let j = 0; j < size; j++) {
            for (let i = size-2; i >= 0; i--) {
                if (board[i][j] !== 0) {
                    let row = i;
                    while (row < size-1) {
                        if (board[row+1][j] === 0) {
                            board[row+1][j] = board[row][j];
                            board[row][j] = 0;
                            row++;
                            moved = true;
                        } else if (board[row+1][j] === board[row][j]) {
                            board[row+1][j] *= 2;
                            score += board[row+1][j];
                            board[row][j] = 0;
                            moved = true;
                            break;
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        scoreElement.textContent = score;
        return moved;
    }

    // 向左移动
    function moveLeft() {
        let moved = false;
        for (let i = 0; i < size; i++) {
            for (let j = 1; j < size; j++) {
                if (board[i][j] !== 0) {
                    let col = j;
                    while (col > 0) {
                        if (board[i][col-1] === 0) {
                            board[i][col-1] = board[i][col];
                            board[i][col] = 0;
                            col--;
                            moved = true;
                        } else if (board[i][col-1] === board[i][col]) {
                            board[i][col-1] *= 2;
                            score += board[i][col-1];
                            board[i][col] = 0;
                            moved = true;
                            break;
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        scoreElement.textContent = score;
        return moved;
    }

    // 向右移动
    function moveRight() {
        let moved = false;
        for (let i = 0; i < size; i++) {
            for (let j = size-2; j >= 0; j--) {
                if (board[i][j] !== 0) {
                    let col = j;
                    while (col < size-1) {
                        if (board[i][col+1] === 0) {
                            board[i][col+1] = board[i][col];
                            board[i][col] = 0;
                            col++;
                            moved = true;
                        } else if (board[i][col+1] === board[i][col]) {
                            board[i][col+1] *= 2;
                            score += board[i][col+1];
                            board[i][col] = 0;
                            moved = true;
                            break;
                        } else {
                            break;
                        }
                    }
                }
            }
        }
        scoreElement.textContent = score;
        return moved;
    }

    // 检查游戏是否结束
    function checkGameOver() {
        // 检查是否有空格
        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                if (board[i][j] === 0) return;
            }
        }

        // 检查是否有相邻的相同数字
        for (let i = 0; i < size; i++) {
            for (let j = 0; j < size; j++) {
                if (j < size-1 && board[i][j] === board[i][j+1]) return;
                if (i < size-1 && board[i][j] === board[i+1][j]) return;
            }
        }

        gameOver = true;
        alert(`游戏结束！最终得分：${score}`);
    }

    // 键盘控制
    document.addEventListener('keydown', (e) => {
        switch(e.key) {
            case 'ArrowUp':
                e.preventDefault();
                move('up');
                break;
            case 'ArrowDown':
                e.preventDefault();
                move('down');
                break;
            case 'ArrowLeft':
                e.preventDefault();
                move('left');
                break;
            case 'ArrowRight':
                e.preventDefault();
                move('right');
                break;
        }
    });

    // 触摸控制
    let touchStartX = 0;
    let touchStartY = 0;

    gameBoard.addEventListener('touchstart', (e) => {
        touchStartX = e.touches[0].clientX;
        touchStartY = e.touches[0].clientY;
    });

    gameBoard.addEventListener('touchend', (e) => {
        const touchEndX = e.changedTouches[0].clientX;
        const touchEndY = e.changedTouches[0].clientY;
        
        const dx = touchEndX - touchStartX;
        const dy = touchEndY - touchStartY;
        
        if (Math.abs(dx) > Math.abs(dy)) {
            if (dx > 0) {
                move('right');
            } else {
                move('left');
            }
        } else {
            if (dy > 0) {
                move('down');
            } else {
                move('up');
            }
        }
    });

    newGameBtn.addEventListener('click', initBoard);

    // 初始化游戏
    initBoard();
}

// 俄罗斯方块游戏
function initTetrisGame() {
    const gameContainer = document.getElementById('gameContainer');
    gameContainer.innerHTML = `
        <div class="game-wrapper">
            <div class="game-status">
                <div>分数: <span id="score">0</span></div>
                <div>等级: <span id="level">1</span></div>
                <div>消除行数: <span id="lines">0</span></div>
            </div>
            <canvas id="tetrisCanvas" width="300" height="600"></canvas>
            <div class="game-controls">
                <button id="startBtn">开始游戏</button>
                <button id="pauseBtn">暂停</button>
            </div>
        </div>
    `;

    const canvas = document.getElementById('tetrisCanvas');
    const ctx = canvas.getContext('2d');
    const scoreDisplay = document.getElementById('score');
    const levelDisplay = document.getElementById('level');
    const linesDisplay = document.getElementById('lines');
    const startBtn = document.getElementById('startBtn');
    const pauseBtn = document.getElementById('pauseBtn');

    const BLOCK_SIZE = 30;
    const COLS = 10;
    const ROWS = 20;
    let score = 0;
    let level = 1;
    let lines = 0;
    let gameOver = false;
    let isPaused = false;
    let dropInterval = 1000;
    let lastTime = 0;
    let dropCounter = 0;
    let board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
    let currentPiece = null;
    let nextPiece = null;

    const PIECES = [
        {
            shape: [[1, 1, 1, 1]],
            color: '#00f0f0'
        },
        {
            shape: [[1, 1], [1, 1]],
            color: '#f0f000'
        },
        {
            shape: [[1, 1, 1], [0, 1, 0]],
            color: '#a000f0'
        },
        {
            shape: [[1, 1, 1], [1, 0, 0]],
            color: '#f0a000'
        },
        {
            shape: [[1, 1, 1], [0, 0, 1]],
            color: '#0000f0'
        },
        {
            shape: [[1, 1, 0], [0, 1, 1]],
            color: '#00f000'
        },
        {
            shape: [[0, 1, 1], [1, 1, 0]],
            color: '#f00000'
        }
    ];

    function createPiece() {
        const piece = PIECES[Math.floor(Math.random() * PIECES.length)];
        return {
            shape: piece.shape,
            color: piece.color,
            x: Math.floor(COLS / 2) - Math.floor(piece.shape[0].length / 2),
            y: 0
        };
    }

    function drawBlock(x, y, color) {
        ctx.fillStyle = color;
        ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE - 1, BLOCK_SIZE - 1);
        ctx.strokeStyle = '#000';
        ctx.strokeRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE - 1, BLOCK_SIZE - 1);
    }

    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        
        // 绘制已固定的方块
        board.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value) {
                    drawBlock(x, y, value);
                }
            });
        });

        // 绘制当前方块
        if (currentPiece) {
            currentPiece.shape.forEach((row, y) => {
                row.forEach((value, x) => {
                    if (value) {
                        drawBlock(currentPiece.x + x, currentPiece.y + y, currentPiece.color);
                    }
                });
            });
        }
    }

    function collision(piece, offsetX = 0, offsetY = 0) {
        return piece.shape.some((row, y) => {
            return row.some((value, x) => {
                if (!value) return false;
                const newX = piece.x + x + offsetX;
                const newY = piece.y + y + offsetY;
                return newX < 0 || newX >= COLS || newY >= ROWS || (newY >= 0 && board[newY][newX]);
            });
        });
    }

    function merge() {
        currentPiece.shape.forEach((row, y) => {
            row.forEach((value, x) => {
                if (value) {
                    board[currentPiece.y + y][currentPiece.x + x] = currentPiece.color;
                }
            });
        });
    }

    function rotate() {
        const newShape = currentPiece.shape[0].map((_, i) =>
            currentPiece.shape.map(row => row[i]).reverse()
        );
        const oldShape = currentPiece.shape;
        currentPiece.shape = newShape;
        if (collision(currentPiece)) {
            currentPiece.shape = oldShape;
        }
    }

    function moveDown() {
        currentPiece.y++;
        if (collision(currentPiece)) {
            currentPiece.y--;
            merge();
            clearLines();
            currentPiece = nextPiece;
            nextPiece = createPiece();
            if (collision(currentPiece)) {
                gameOver = true;
            }
        }
        dropCounter = 0;
    }

    function moveLeft() {
        currentPiece.x--;
        if (collision(currentPiece)) {
            currentPiece.x++;
        }
    }

    function moveRight() {
        currentPiece.x++;
        if (collision(currentPiece)) {
            currentPiece.x--;
        }
    }

    function clearLines() {
        let linesCleared = 0;
        outer: for (let y = ROWS - 1; y >= 0; y--) {
            for (let x = 0; x < COLS; x++) {
                if (!board[y][x]) continue outer;
            }
            const row = board.splice(y, 1)[0].fill(0);
            board.unshift(row);
            y++;
            linesCleared++;
        }
        if (linesCleared > 0) {
            score += linesCleared * 100 * level;
            lines += linesCleared;
            level = Math.floor(lines / 10) + 1;
            dropInterval = Math.max(100, 1000 - (level - 1) * 100);
            scoreDisplay.textContent = score;
            levelDisplay.textContent = level;
            linesDisplay.textContent = lines;
        }
    }

    function update(time = 0) {
        if (gameOver || isPaused) return;

        const deltaTime = time - lastTime;
        lastTime = time;
        dropCounter += deltaTime;
        if (dropCounter > dropInterval) {
            moveDown();
        }
        draw();
        requestAnimationFrame(update);
    }

    function reset() {
        board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
        score = 0;
        level = 1;
        lines = 0;
        gameOver = false;
        isPaused = false;
        dropInterval = 1000;
        scoreDisplay.textContent = score;
        levelDisplay.textContent = level;
        linesDisplay.textContent = lines;
        currentPiece = createPiece();
        nextPiece = createPiece();
        update();
    }

    // 键盘控制
    document.addEventListener('keydown', event => {
        if (gameOver || isPaused) return;
        switch (event.keyCode) {
            case 37: // 左箭头
                moveLeft();
                break;
            case 39: // 右箭头
                moveRight();
                break;
            case 40: // 下箭头
                moveDown();
                break;
            case 38: // 上箭头
                rotate();
                break;
            case 32: // 空格
                while (!collision(currentPiece, 0, 1)) {
                    currentPiece.y++;
                }
                moveDown();
                break;
        }
    });

    // 按钮控制
    startBtn.addEventListener('click', () => {
        if (gameOver) {
            reset();
        } else if (isPaused) {
            isPaused = false;
            update();
        }
    });

    pauseBtn.addEventListener('click', () => {
        if (!gameOver) {
            isPaused = !isPaused;
            if (!isPaused) {
                update();
            }
        }
    });

    // 初始化游戏
    reset();
} 

// 密码生成器功能
function initPasswordGenerator() {
    const lengthSlider = document.getElementById('passwordLength');
    const lengthValue = document.getElementById('lengthValue');
    const includeUppercase = document.getElementById('includeUppercase');
    const includeLowercase = document.getElementById('includeLowercase');
    const includeNumbers = document.getElementById('includeNumbers');
    const includeSymbols = document.getElementById('includeSymbols');
    const generatedPassword = document.getElementById('generatedPassword');
    const copyBtn = document.querySelector('.copy-btn');
    const refreshBtn = document.querySelector('.refresh-btn');
    const strengthBar = document.querySelector('.strength-bar');
    const strengthText = document.querySelector('.strength-text');

    const chars = {
        uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        lowercase: 'abcdefghijklmnopqrstuvwxyz',
        numbers: '0123456789',
        symbols: '!@#$%^&*()_+-=[]{}|;:,.<>?'
    };

    function generatePassword() {
        const length = parseInt(lengthSlider.value);
        let charPool = '';
        let password = '';

        if (includeUppercase.checked) charPool += chars.uppercase;
        if (includeLowercase.checked) charPool += chars.lowercase;
        if (includeNumbers.checked) charPool += chars.numbers;
        if (includeSymbols.checked) charPool += chars.symbols;

        if (charPool === '') {
            alert('请至少选择一种字符类型！');
            return;
        }

        for (let i = 0; i < length; i++) {
            const randomIndex = Math.floor(Math.random() * charPool.length);
            password += charPool[randomIndex];
        }

        generatedPassword.value = password;
        updatePasswordStrength(password);
    }

    function updatePasswordStrength(password) {
        let strength = 0;
        
        // 长度检查
        if (password.length >= 8) strength += 1;
        if (password.length >= 12) strength += 1;
        
        // 字符类型检查
        if (/[A-Z]/.test(password)) strength += 1;
        if (/[a-z]/.test(password)) strength += 1;
        if (/[0-9]/.test(password)) strength += 1;
        if (/[^A-Za-z0-9]/.test(password)) strength += 1;

        // 更新UI
        const strengthPercent = (strength / 6) * 100;
        strengthBar.style.width = `${strengthPercent}%`;

        // 设置颜色
        if (strength <= 2) {
            strengthBar.style.backgroundColor = '#ff4444';
            strengthText.textContent = '密码强度：弱';
        } else if (strength <= 4) {
            strengthBar.style.backgroundColor = '#ffbb33';
            strengthText.textContent = '密码强度：中等';
        } else {
            strengthBar.style.backgroundColor = '#00C851';
            strengthText.textContent = '密码强度：强';
        }
    }

    lengthSlider.addEventListener('input', () => {
        lengthValue.textContent = lengthSlider.value;
        generatePassword();
    });

    [includeUppercase, includeLowercase, includeNumbers, includeSymbols].forEach(checkbox => {
        checkbox.addEventListener('change', generatePassword);
    });

    copyBtn.addEventListener('click', () => {
        generatedPassword.select();
        document.execCommand('copy');
        showToast('密码已复制到剪贴板');
    });

    refreshBtn.addEventListener('click', generatePassword);

    // 初始生成密码
    generatePassword();
}

// 加密解密工具功能
function initEncryptionTool() {
    const modeBtns = document.querySelectorAll('.encryption-mode .mode-btn');
    const encryptInput = document.getElementById('encryptInput');
    const encryptOutput = document.getElementById('encryptOutput');
    const encryptionMethod = document.getElementById('encryptionMethod');
    const keyGroup = document.getElementById('keyGroup');
    const encryptionKey = document.getElementById('encryptionKey');
    const copyBtn = document.querySelector('.encryption-result .copy-btn');

    let currentMode = 'encrypt';

    function updateMode(mode) {
        currentMode = mode;
        modeBtns.forEach(btn => {
            btn.classList.toggle('active', btn.dataset.mode === mode);
        });
        encryptInput.placeholder = mode === 'encrypt' ? 
            '输入要加密的文本...' : '输入要解密的文本...';
    }

    function encryptAES(text, key) {
        // 使用 CryptoJS 库进行 AES 加密
        const encrypted = CryptoJS.AES.encrypt(text, key);
        return encrypted.toString();
    }

    function decryptAES(text, key) {
        try {
            const decrypted = CryptoJS.AES.decrypt(text, key);
            return decrypted.toString(CryptoJS.enc.Utf8);
        } catch (e) {
            return '解密失败：密钥可能不正确';
        }
    }

    function encryptBase64(text) {
        return btoa(encodeURIComponent(text));
    }

    function decryptBase64(text) {
        try {
            return decodeURIComponent(atob(text));
        } catch (e) {
            return '解密失败：输入格式不正确';
        }
    }

    function encryptCaesar(text, shift) {
        return text.split('').map(char => {
            const code = char.charCodeAt(0);
            if (code >= 65 && code <= 90) { // 大写字母
                return String.fromCharCode((code - 65 + shift) % 26 + 65);
            } else if (code >= 97 && code <= 122) { // 小写字母
                return String.fromCharCode((code - 97 + shift) % 26 + 97);
            }
            return char;
        }).join('');
    }

    function decryptCaesar(text, shift) {
        return encryptCaesar(text, 26 - shift);
    }

    function processText() {
        const text = encryptInput.value;
        const method = encryptionMethod.value;
        let result = '';

        if (currentMode === 'encrypt') {
            switch (method) {
                case 'aes':
                    if (!encryptionKey.value) {
                        alert('请输入加密密钥！');
                        return;
                    }
                    result = encryptAES(text, encryptionKey.value);
                    break;
                case 'base64':
                    result = encryptBase64(text);
                    break;
                case 'caesar':
                    result = encryptCaesar(text, 3);
                    break;
            }
        } else {
            switch (method) {
                case 'aes':
                    if (!encryptionKey.value) {
                        alert('请输入解密密钥！');
                        return;
                    }
                    result = decryptAES(text, encryptionKey.value);
                    break;
                case 'base64':
                    result = decryptBase64(text);
                    break;
                case 'caesar':
                    result = decryptCaesar(text, 3);
                    break;
            }
        }

        encryptOutput.value = result;
    }

    modeBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            updateMode(btn.dataset.mode);
            processText();
        });
    });

    encryptionMethod.addEventListener('change', () => {
        keyGroup.style.display = encryptionMethod.value === 'aes' ? 'block' : 'none';
        processText();
    });

    encryptInput.addEventListener('input', processText);
    encryptionKey.addEventListener('input', processText);

    copyBtn.addEventListener('click', () => {
        encryptOutput.select();
        document.execCommand('copy');
        showToast('已复制到剪贴板');
    });
}

// 哈希计算器功能
function initHashCalculator() {
    const hashInput = document.getElementById('hashInput');
    const hashFile = document.getElementById('hashFile');
    const hashAlgorithm = document.getElementById('hashAlgorithm');
    const hashOutput = document.getElementById('hashOutput');
    const copyBtn = document.querySelector('.hash-result .copy-btn');
    const fileBtn = document.querySelector('.file-btn');

    async function calculateHash(text) {
        const encoder = new TextEncoder();
        const data = encoder.encode(text);
        const hashBuffer = await crypto.subtle.digest(hashAlgorithm.value, data);
        const hashArray = Array.from(new Uint8Array(hashBuffer));
        return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
    }

    async function calculateFileHash(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = async (e) => {
                try {
                    const data = new Uint8Array(e.target.result);
                    const hashBuffer = await crypto.subtle.digest(hashAlgorithm.value, data);
                    const hashArray = Array.from(new Uint8Array(hashBuffer));
                    resolve(hashArray.map(b => b.toString(16).padStart(2, '0')).join(''));
                } catch (error) {
                    reject(error);
                }
            };
            reader.onerror = reject;
            reader.readAsArrayBuffer(file);
        });
    }

    async function updateHash() {
        if (hashFile.files.length > 0) {
            try {
                const hash = await calculateFileHash(hashFile.files[0]);
                hashOutput.value = hash;
            } catch (error) {
                console.error('计算文件哈希值失败:', error);
                showToast('计算文件哈希值失败');
            }
        } else if (hashInput.value) {
            try {
                const hash = await calculateHash(hashInput.value);
                hashOutput.value = hash;
            } catch (error) {
                console.error('计算文本哈希值失败:', error);
                showToast('计算文本哈希值失败');
            }
        } else {
            hashOutput.value = '';
        }
    }

    hashInput.addEventListener('input', updateHash);
    hashAlgorithm.addEventListener('change', updateHash);
    hashFile.addEventListener('change', updateHash);

    fileBtn.addEventListener('click', () => {
        hashFile.click();
    });

    copyBtn.addEventListener('click', () => {
        hashOutput.select();
        document.execCommand('copy');
        showToast('哈希值已复制到剪贴板');
    });
}

// 正则表达式测试器功能
function initRegexTester() {
    const regexPattern = document.getElementById('regexPattern');
    const regexText = document.getElementById('regexText');
    const globalMatch = document.getElementById('globalMatch');
    const caseInsensitive = document.getElementById('caseInsensitive');
    const multiline = document.getElementById('multiline');
    const matchCount = document.getElementById('matchCount');
    const matchResults = document.getElementById('matchResults');

    function updateMatches() {
        const pattern = regexPattern.value;
        const text = regexText.value;
        let flags = '';
        
        if (globalMatch.checked) flags += 'g';
        if (caseInsensitive.checked) flags += 'i';
        if (multiline.checked) flags += 'm';

        try {
            const regex = new RegExp(pattern, flags);
            const matches = text.matchAll(regex);
            const results = Array.from(matches);

            matchCount.textContent = `${results.length} 个匹配`;
            
            if (results.length > 0) {
                matchResults.innerHTML = results.map((match, index) => {
                    const [fullMatch, ...groups] = match;
                    const groupsHtml = groups.map((group, i) => 
                        `<div class="group">组 ${i + 1}: ${group}</div>`
                    ).join('');
                    
                    return `
                        <div class="match">
                            <div class="match-number">匹配 #${index + 1}</div>
                            <div class="full-match">${fullMatch}</div>
                            ${groupsHtml}
                            <div class="match-position">位置: ${match.index}</div>
                        </div>
                    `;
                }).join('');
            } else {
                matchResults.innerHTML = '<div class="no-matches">没有找到匹配</div>';
            }
        } catch (error) {
            matchCount.textContent = '正则表达式错误';
            matchResults.innerHTML = `<div class="error">${error.message}</div>`;
        }
    }

    regexPattern.addEventListener('input', updateMatches);
    regexText.addEventListener('input', updateMatches);
    globalMatch.addEventListener('change', updateMatches);
    caseInsensitive.addEventListener('change', updateMatches);
    multiline.addEventListener('change', updateMatches);
}

// JSON格式化工具功能
function initJsonFormatter() {
    const jsonInput = document.getElementById('jsonInput');
    const jsonOutput = document.getElementById('jsonOutput');
    const jsonStatus = document.getElementById('jsonStatus');
    const formatBtn = document.querySelector('.format-btn');
    const minifyBtn = document.querySelector('.minify-btn');
    const validateBtn = document.querySelector('.validate-btn');
    const copyBtn = document.querySelector('.json-actions .copy-btn');

    function formatJson(json) {
        try {
            const parsed = JSON.parse(json);
            return JSON.stringify(parsed, null, 4);
        } catch (error) {
            throw new Error('无效的 JSON 格式');
        }
    }

    function minifyJson(json) {
        try {
            const parsed = JSON.parse(json);
            return JSON.stringify(parsed);
        } catch (error) {
            throw new Error('无效的 JSON 格式');
        }
    }

    function validateJson(json) {
        try {
            JSON.parse(json);
            return true;
        } catch (error) {
            return false;
        }
    }

    function updateStatus(message, isError = false) {
        jsonStatus.textContent = message;
        jsonStatus.style.color = isError ? '#ff4444' : '#00C851';
    }

    formatBtn.addEventListener('click', () => {
        try {
            const formatted = formatJson(jsonInput.value);
            jsonOutput.textContent = formatted;
            updateStatus('JSON 格式化成功');
        } catch (error) {
            updateStatus(error.message, true);
        }
    });

    minifyBtn.addEventListener('click', () => {
        try {
            const minified = minifyJson(jsonInput.value);
            jsonOutput.textContent = minified;
            updateStatus('JSON 压缩成功');
        } catch (error) {
            updateStatus(error.message, true);
        }
    });

    validateBtn.addEventListener('click', () => {
        if (validateJson(jsonInput.value)) {
            updateStatus('JSON 格式有效');
        } else {
            updateStatus('JSON 格式无效', true);
        }
    });

    copyBtn.addEventListener('click', () => {
        if (jsonOutput.textContent) {
            const text = jsonOutput.textContent;
            navigator.clipboard.writeText(text).then(() => {
                showToast('已复制到剪贴板');
            }).catch(() => {
                const textarea = document.createElement('textarea');
                textarea.value = text;
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                showToast('已复制到剪贴板');
            });
        }
    });
}

// 初始化所有新工具
function initNewTools() {
    initPasswordGenerator();
    initEncryptionTool();
    initHashCalculator();
    initRegexTester();
    initJsonFormatter();
}

// 在页面加载完成后初始化新工具
document.addEventListener('DOMContentLoaded', () => {
    // ... existing code ...
    initNewTools();
});

// ... existing code ...

// 初始化关于我们页面
function initAboutPage() {
    // 添加工具卡片动画
    const toolCards = document.querySelectorAll('.tool-card');
    toolCards.forEach((card, index) => {
        card.style.animationDelay = `${index * 0.1}s`;
        card.classList.add('fade-in');
    });

    // 添加特性列表项动画
    const featureItems = document.querySelectorAll('.feature-list li');
    featureItems.forEach((item, index) => {
        item.style.animationDelay = `${index * 0.1}s`;
        item.classList.add('slide-in');
    });
}

// 在页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
    // ... existing code ...
    initAboutPage();
});

// ... existing code ...

// 作者信息悬浮窗关闭按钮逻辑
function initAuthorCloseBtns() {
    document.querySelectorAll('.close-author-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            this.parentElement.style.display = 'none';
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    // ... existing code ...
    initAuthorCloseBtns();
    // 自动淡出作者信息悬浮窗
    setTimeout(() => {
        document.querySelectorAll('.floating-author').forEach(el => {
            el.classList.add('fade-out');
        });
    }, 5000);
});
// ... existing code ...